package com.ktjy.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.pojo.SysRole;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ISysRoleService;
import com.ktjy.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hjy
 * @since 2025-01-09
 */
@Controller
@RequestMapping("/user")
public class SysUserController {
    @Resource
    ISysUserService sysUserService;
    @Resource
    ISysRoleService sysRoleService;

    @RequestMapping("/list")
    public String list(SysUser sysUser,
                       @RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
                       Model model){
        IPage<SysUser> page = sysUserService.getPage(sysUser, pageIndex, pageSize);
        model.addAttribute("userPager",page);
        //回显数据
        model.addAttribute("condition",sysUser);

        return "user/list";
    }

    @GetMapping("/add")
    public String save(Model model){
        List<SysRole> roles=sysRoleService.list();
        model.addAttribute("roles",roles);
        return "user/add";
    }

    @PostMapping("/save")
    public String save(SysUser sysUser){
        boolean ok=false;
        if (sysUser.getUsrId()==null){
            ok=sysUserService.save(sysUser);
        }else {
            ok=sysUserService.updateById(sysUser);
        }
        if (ok){
            return "redirect:/user/list";
        }
        return "user/add";
    }

    @GetMapping("/edit")
    public String edit(Model model,@RequestParam("usrId") Integer usrId){
        SysUser user=sysUserService.getById(usrId);
        List<SysRole> roles=sysRoleService.list();
        model.addAttribute("roles",roles);
        model.addAttribute("user",user);
        return "user/edit";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Integer id){
        Map<String,Object> map=new HashMap<>();
        boolean ok=sysUserService.removeById(id);
        if (ok){
            map.put("delResult",true);
        }else {
            map.put("delResult",false);
        }
        return map;
    }
}
